import {
  type Action,
  ElMessage,
  ElMessageBox,
} from 'element-plus'
import type { MaybeRefOrGetter } from 'vue'
import type { Tree } from '../ViewTree/type'
import { indicatorApi } from '@/api'
import { useDefineLoading } from '@/hooks'
import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/message-box/style/css'
import type { IndicatorInfo } from '@/types'

export function useIndicatorTable(
  point: MaybeRefOrGetter<Tree>,
  isVirtually?: 0 | 1,
  clickIndicatorNameHandler?: (row: IndicatorInfo) => void,
) {
  const { withLoading, vLoading } = useDefineLoading()
  const tableData = ref<IndicatorInfo[]>([])

  const getTableData = async () => {
    const { id: pointId = 0 } = toValue(point)

    try {
      tableData.value = []
      const { data } = await withLoading(
        indicatorApi.loadPointList,
      )(pointId, isVirtually)
      tableData.value = data || []
    }
    catch (e) {}
  }

  const deleteData = async (id: number) => {
    const res: Action = await ElMessageBox.confirm(
      '该操作将永久删除该数据，确定删除？',
      '警告',
      {
        type: 'warning',
      },
    ).catch(e => e)

    if (res !== 'confirm')
      return
    try {
      const { code } = await indicatorApi.deleteIndicatorById(
        id,
      )
      if (code !== 200) {
        ElMessage.info('删除失败，请稍后再试！')
        return
      }
      getTableData()
      ElMessage.success('删除成功！')
    }
    catch (e) {}
  }

  const clickIndicatorName = (row: IndicatorInfo) => {
    clickIndicatorNameHandler?.(row)
  }

  return {
    tableData,

    vLoading,
    withLoading,

    /** 查询指标列表数据 */
    getTableData,

    /** 点击删除列表一行 */
    deleteData,

    /** 点击指标名称跳转 */
    clickIndicatorName,
  }
}
